package com.w.work3_18;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private TextView txt_result;
    private Spinner se_pro;
    private Spinner se_city;
    private Spinner se_area;

    private String[] ProvinceDatas;
    private String[] CityDatas;
    private String[] AreaDatas;

    //列表选择的 省市区
    private String selectedPro = "";
    private String selectedCity = "";
    private String selectedArea = "";

    //适配器
    private ArrayAdapter<String> ProvinceAdapter;
    private ArrayAdapter<String> CityAdapter;
    private ArrayAdapter<String> AreaAdapter;

    //存储省对应的所有市区
    private Map<String,String[]> cityDataMap = new HashMap<String, String[]>();
    //存储市对应的所有地区
    private Map<String,String[]> areaDataMap = new HashMap<String, String[]>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txt_result=findViewById(R.id.txt_result);
        se_pro = findViewById(R.id.se_pro);
        se_city = findViewById(R.id.se_city);
        se_area = findViewById(R.id.se_area);

        try {
            InputStream inputStream = getResources().getAssets().open("data.txt");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer stringBuffer = new StringBuffer();
            String line = bufferedReader.readLine();
            while (line!=null){
                stringBuffer.append(line);
                line = bufferedReader.readLine();
            }
            //开始解析
            JSONArray jsonArray = new JSONArray(stringBuffer.toString());
            ProvinceDatas = new String[jsonArray.length()];
            String provinceStr = null;
            //循环遍历省份，并保存
            for (int i=0;i<jsonArray.length();i++){
                JSONObject provinceObject = jsonArray.getJSONObject(i);
                provinceStr=provinceObject.getString("name");
                ProvinceDatas[i]=provinceStr;

                JSONArray cityArray;
                String cityStr=null;

                try {
                    cityArray = provinceObject.getJSONArray("city");
                }
               catch (Exception e){
                    e.printStackTrace();
                    continue;
               }
               CityDatas = new String[cityArray.length()];
                //循环遍历城市，并保存
                for (int j=0;j<cityArray.length();j++){
                    JSONObject cityObject = cityArray.getJSONObject(j);
                    cityStr=cityObject.getString("name");
                    CityDatas[j]=cityStr;

                    JSONArray areaArray;
                    try {
                        areaArray = cityObject.getJSONArray("area");
                    }catch (Exception e){
                        e.printStackTrace();
                        continue;
                    }
                    AreaDatas = new String[areaArray.length()];
                    //循环遍历地区，并保存
                    for (int k=0;k<areaArray.length();k++){
                        AreaDatas[k]=areaArray.getString(k);
                    }
                    //存储区
                    areaDataMap.put(cityStr,AreaDatas);
                }
                //存储市
                cityDataMap.put(provinceStr,CityDatas);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ProvinceAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,ProvinceDatas);
        ProvinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        se_pro.setAdapter(ProvinceAdapter);
        //省份选择
        se_pro.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedPro="";
                selectedPro = (String) parent.getSelectedItem();
                //根据省份更新城市区域信息
                updateCity(selectedPro);
                Log.e(TAG,"selectedPro="+selectedPro);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        se_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedCity="";
                selectedCity = (String) parent.getSelectedItem();
                //根据市选择区信息
                updataArea(selectedCity);
                Log.e(TAG,"selectedCity = "+selectedCity);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        se_area.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedArea="";
                selectedArea = (String) parent.getSelectedItem();
                txt_result.setText("你选择了："+selectedPro+selectedCity+selectedArea);
                Log.e(TAG,"selectedArea="+selectedArea);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void updataArea(String city) {
        String[] areas = areaDataMap.get(city);
        //判断是否存在地区
        if (areas!=null){
            se_area.setVisibility(View.VISIBLE);
            AreaAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,areas);
            AreaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            se_area.setAdapter(AreaAdapter);
            AreaAdapter.notifyDataSetChanged();
            se_area.setSelection(0);
        }else {
            txt_result.setText("你选择了："+selectedPro+selectedCity);
            se_area.setVisibility(View.GONE);
        }
    }

    private void updateCity(String Pro) {
        String cities[] = cityDataMap.get(Pro);
        for (int i=0;i<cities.length;i++){
            CityAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,cities);
            CityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            se_city.setAdapter(CityAdapter);
            CityAdapter.notifyDataSetChanged();
            se_city.setSelection(0);
        }
    }
}
